<template>
  <div v-if="modelValue" class="modal-overlay" @click="handleOverlayClick">
    <div class="apple-card modal-dialog large-dialog" @click.stop>
      <div class="apple-card__header">
        <h2 class="text-heading">新建用户</h2>
        <button 
          class="close-button apple-button apple-button--text"
          @click="handleClose"
        >
          ✕
        </button>
      </div>

      <form class="apple-card__body" @submit.prevent="handleSubmit">
        <div class="form-sections">
          <!-- 基本信息 -->
          <div class="form-section">
            <h3 class="section-title">基本信息</h3>
            
            <div class="form-row">
              <div class="form-group">
                <label class="form-label">用户名 *</label>
                <input
                  v-model="form.username"
                  class="apple-input"
                  :class="{ 'apple-input--error': errors.username }"
                  placeholder="请输入用户名"
                  maxlength="50"
                  required
                >
                <div v-if="errors.username" class="error-message">{{ errors.username }}</div>
                <div class="form-help">只能包含字母、数字、下划线和连字符</div>
              </div>

              <div class="form-group">
                <label class="form-label">真实姓名 *</label>
                <input
                  v-model="form.real_name"
                  class="apple-input"
                  :class="{ 'apple-input--error': errors.real_name }"
                  placeholder="请输入真实姓名"
                  maxlength="50"
                  required
                >
                <div v-if="errors.real_name" class="error-message">{{ errors.real_name }}</div>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label class="form-label">邮箱地址 *</label>
                <input
                  v-model="form.email"
                  type="email"
                  class="apple-input"
                  :class="{ 'apple-input--error': errors.email }"
                  placeholder="请输入邮箱地址"
                  required
                >
                <div v-if="errors.email" class="error-message">{{ errors.email }}</div>
              </div>

              <div class="form-group">
                <label class="form-label">手机号</label>
                <input
                  v-model="form.phone"
                  class="apple-input"
                  :class="{ 'apple-input--error': errors.phone }"
                  placeholder="请输入手机号"
                  maxlength="20"
                >
                <div v-if="errors.phone" class="error-message">{{ errors.phone }}</div>
              </div>
            </div>

            <div class="form-group">
              <label class="form-label">密码 *</label>
              <div class="password-input-wrapper">
                <input
                  v-model="form.password"
                  :type="showPassword ? 'text' : 'password'"
                  class="apple-input"
                  :class="{ 'apple-input--error': errors.password }"
                  placeholder="请输入密码"
                  minlength="6"
                  required
                >
                <button
                  type="button"
                  class="password-toggle"
                  @click="showPassword = !showPassword"
                >
                  {{ showPassword ? '👁️' : '🙈' }}
                </button>
              </div>
              <div v-if="errors.password" class="error-message">{{ errors.password }}</div>
              <div class="form-help">密码长度至少6位</div>
            </div>
          </div>

          <!-- 组织信息 -->
          <div class="form-section">
            <h3 class="section-title">组织信息</h3>
            
            <div class="form-row">
              <div class="form-group">
                <label class="form-label">员工编号</label>
                <input
                  v-model="form.employee_id"
                  class="apple-input"
                  :class="{ 'apple-input--error': errors.employee_id }"
                  placeholder="请输入员工编号"
                  maxlength="20"
                >
                <div v-if="errors.employee_id" class="error-message">{{ errors.employee_id }}</div>
              </div>

              <div class="form-group">
                <label class="form-label">部门</label>
                <input
                  v-model="form.department"
                  class="apple-input"
                  placeholder="请输入部门"
                  maxlength="50"
                  list="departments"
                >
                <datalist id="departments">
                  <option v-for="dept in departments" :key="dept" :value="dept">
                </datalist>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label class="form-label">职位</label>
                <input
                  v-model="form.position"
                  class="apple-input"
                  placeholder="请输入职位"
                  maxlength="50"
                >
              </div>

              <div class="form-group">
                <label class="form-label">直属领导</label>
                <select v-model="form.manager_id" class="apple-input">
                  <option value="">无直属领导</option>
                  <option 
                    v-for="manager in managers" 
                    :key="manager.id" 
                    :value="manager.id"
                  >
                    {{ manager.real_name }} ({{ manager.username }})
                  </option>
                </select>
              </div>
            </div>
          </div>

          <!-- 角色与权限 -->
          <div class="form-section">
            <h3 class="section-title">角色与权限</h3>
            
            <div class="form-group">
              <label class="form-label">用户状态</label>
              <select v-model="form.status" class="apple-input">
                <option value="active">激活</option>
                <option value="inactive">未激活</option>
              </select>
              <div class="form-help">新用户建议设为"未激活"，创建后再手动激活</div>
            </div>

            <div class="form-group">
              <label class="form-label">分配角色</label>
              <div class="roles-selection">
                <div 
                  v-for="role in availableRoles" 
                  :key="role.id"
                  class="role-item"
                  :class="{ 'role-item--selected': form.role_ids.includes(role.id) }"
                  @click="toggleRole(role.id)"
                >
                  <div class="role-info">
                    <div class="role-name">{{ role.name }}</div>
                    <div class="role-description">{{ role.description || '暂无描述' }}</div>
                  </div>
                  <div class="role-checkbox">
                    <div 
                      class="apple-switch apple-switch--small"
                      :class="{ 'apple-switch--active': form.role_ids.includes(role.id) }"
                    ></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </form>

      <div class="apple-card__footer">
        <button 
          type="button"
          class="apple-button apple-button--secondary"
          @click="handleClose"
        >
          取消
        </button>
        <button 
          type="submit"
          class="apple-button apple-button--primary"
          :disabled="!isFormValid || submitting"
          @click="handleSubmit"
        >
          {{ submitting ? '创建中...' : '创建用户' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { userApi } from '@/api/users'
import { roleApi, userApi as userDataApi } from '@/api/rbac'
import type { Role, User } from '@/types/rbac'

// Props
interface Props {
  modelValue: boolean
}

// Emits
interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'created'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 表单数据
const form = ref({
  username: '',
  real_name: '',
  email: '',
  phone: '',
  password: '',
  employee_id: '',
  department: '',
  position: '',
  manager_id: null as number | null,
  status: 'active' as const,
  role_ids: [] as number[]
})

// 表单验证错误
const errors = ref({
  username: '',
  real_name: '',
  email: '',
  phone: '',
  password: '',
  employee_id: ''
})

// 状态
const submitting = ref(false)
const showPassword = ref(false)
const availableRoles = ref<Role[]>([])
const managers = ref<User[]>([])
const departments = ref<string[]>([])

// 计算属性
const isFormValid = computed(() => {
  return form.value.username.trim() && 
         form.value.real_name.trim() && 
         form.value.email.trim() && 
         form.value.password.trim() &&
         !Object.values(errors.value).some(error => error)
})

// 验证函数
const validateUsername = () => {
  const username = form.value.username.trim()
  if (!username) {
    errors.value.username = '用户名不能为空'
  } else if (username.length < 3) {
    errors.value.username = '用户名至少3个字符'
  } else if (!/^[a-zA-Z0-9_-]+$/.test(username)) {
    errors.value.username = '只能包含字母、数字、下划线和连字符'
  } else {
    errors.value.username = ''
  }
}

const validateRealName = () => {
  const realName = form.value.real_name.trim()
  if (!realName) {
    errors.value.real_name = '真实姓名不能为空'
  } else {
    errors.value.real_name = ''
  }
}

const validateEmail = () => {
  const email = form.value.email.trim()
  if (!email) {
    errors.value.email = '邮箱地址不能为空'
  } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
    errors.value.email = '邮箱格式不正确'
  } else {
    errors.value.email = ''
  }
}

const validatePhone = () => {
  const phone = form.value.phone.trim()
  if (phone && !/^[\d\-\+\s]+$/.test(phone)) {
    errors.value.phone = '手机号格式不正确'
  } else {
    errors.value.phone = ''
  }
}

const validatePassword = () => {
  const password = form.value.password
  if (!password) {
    errors.value.password = '密码不能为空'
  } else if (password.length < 6) {
    errors.value.password = '密码至少6个字符'
  } else {
    errors.value.password = ''
  }
}

const validateEmployeeId = () => {
  // 员工编号为可选字段，此处可以添加特定的验证逻辑
  errors.value.employee_id = ''
}

// 角色选择
const toggleRole = (roleId: number) => {
  const index = form.value.role_ids.indexOf(roleId)
  if (index > -1) {
    form.value.role_ids.splice(index, 1)
  } else {
    form.value.role_ids.push(roleId)
  }
}

// 加载数据
const loadRoles = async () => {
  try {
    const response = await roleApi.getRoles({ size: 100 })
    if (response.success) {
      availableRoles.value = response.data.filter(role => role.is_active && !role.is_system)
    }
  } catch (error) {
    console.error('加载角色失败:', error)
  }
}

const loadManagers = async () => {
  try {
    const response = await userDataApi.getUsers({ size: 100, status: 'active' })
    if (response.success) {
      managers.value = response.data
    }
  } catch (error) {
    console.error('加载管理者列表失败:', error)
  }
}

const loadDepartments = async () => {
  try {
    const response = await userDataApi.getUsers({ size: 1000 })
    if (response.success) {
      const deptSet = new Set(response.data.map(u => u.department).filter(Boolean))
      departments.value = Array.from(deptSet).sort()
    }
  } catch (error) {
    console.error('加载部门列表失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  form.value = {
    username: '',
    real_name: '',
    email: '',
    phone: '',
    password: '',
    employee_id: '',
    department: '',
    position: '',
    manager_id: null,
    status: 'active',
    role_ids: []
  }
  
  errors.value = {
    username: '',
    real_name: '',
    email: '',
    phone: '',
    password: '',
    employee_id: ''
  }
  
  showPassword.value = false
}

// 关闭对话框
const handleClose = () => {
  emit('update:modelValue', false)
}

// 点击遮罩关闭
const handleOverlayClick = () => {
  handleClose()
}

// 提交表单
const handleSubmit = async () => {
  // 执行所有验证
  validateUsername()
  validateRealName()
  validateEmail()
  validatePhone()
  validatePassword()
  validateEmployeeId()
  
  if (!isFormValid.value) {
    return
  }
  
  submitting.value = true
  
  try {
    const requestData = {
      username: form.value.username.trim(),
      real_name: form.value.real_name.trim(),
      email: form.value.email.trim(),
      password: form.value.password,
      phone: form.value.phone.trim() || undefined,
      employee_id: form.value.employee_id.trim() || undefined,
      department: form.value.department.trim() || undefined,
      position: form.value.position.trim() || undefined,
      manager_id: form.value.manager_id || undefined,
      status: form.value.status,
      role_ids: form.value.role_ids.length > 0 ? form.value.role_ids : undefined
    }
    
    const response = await userApi.createUser(requestData)
    
    if (response.success) {
      emit('created')
      handleClose()
      ElMessage.success('用户创建成功')
    }
  } catch (error: any) {
    console.error('创建用户失败:', error)
    
    // 处理特定错误
    if (error.response?.data?.detail) {
      const detail = error.response.data.detail
      if (detail.includes('用户名已存在')) {
        errors.value.username = '用户名已存在'
      } else if (detail.includes('邮箱已存在')) {
        errors.value.email = '邮箱已存在'
      } else if (detail.includes('员工编号已存在')) {
        errors.value.employee_id = '员工编号已存在'
      } else {
        ElMessage.error(detail)
      }
    } else {
      ElMessage.error('创建用户失败')
    }
  } finally {
    submitting.value = false
  }
}

// 监听表单变化
watch(() => form.value.username, validateUsername)
watch(() => form.value.real_name, validateRealName)
watch(() => form.value.email, validateEmail)
watch(() => form.value.phone, validatePhone)
watch(() => form.value.password, validatePassword)
watch(() => form.value.employee_id, validateEmployeeId)

// 监听对话框打开
watch(() => props.modelValue, (newValue) => {
  if (newValue) {
    resetForm()
    loadRoles()
    loadManagers()
    loadDepartments()
  }
})

onMounted(() => {
  if (props.modelValue) {
    loadRoles()
    loadManagers()
    loadDepartments()
  }
})
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: var(--spacing-lg);
}

.large-dialog {
  width: 100%;
  max-width: 700px;
  max-height: 90vh;
  overflow-y: auto;
  animation: modalSlideIn var(--duration-normal) var(--ease-out);
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.apple-card__header {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.close-button {
  position: absolute;
  right: 0;
  padding: var(--spacing-xs);
  font-size: 18px;
  opacity: 0.6;
}

.close-button:hover {
  opacity: 1;
}

.form-sections {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: var(--spacing-xs);
}

.form-section {
  margin-bottom: var(--spacing-xl);
  padding-bottom: var(--spacing-lg);
  border-bottom: 1px solid var(--border-secondary);
}

.form-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.section-title {
  margin: 0 0 var(--spacing-lg) 0;
  color: var(--color-primary);
  font-size: 16px;
  font-weight: 600;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-md);
}

.form-group {
  margin-bottom: var(--spacing-md);
}

.form-label {
  display: block;
  margin-bottom: var(--spacing-xs);
  font-weight: 500;
  color: var(--text-primary);
}

.form-help {
  margin-top: var(--spacing-xs);
  font-size: 12px;
  color: var(--text-tertiary);
}

.error-message {
  margin-top: var(--spacing-xs);
  font-size: 12px;
  color: var(--color-danger);
}

.password-input-wrapper {
  position: relative;
}

.password-toggle {
  position: absolute;
  right: var(--spacing-sm);
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  cursor: pointer;
  padding: var(--spacing-xs);
  opacity: 0.6;
}

.password-toggle:hover {
  opacity: 1;
}

.roles-selection {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: var(--spacing-sm);
  max-height: 300px;
  overflow-y: auto;
  padding: var(--spacing-sm);
  border: 1px solid var(--border-secondary);
  border-radius: var(--radius-medium);
  background-color: var(--bg-secondary);
}

.role-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--spacing-sm);
  border: 1px solid var(--border-secondary);
  border-radius: var(--radius-medium);
  cursor: pointer;
  transition: all var(--duration-fast) var(--ease-out);
  background-color: var(--bg-primary);
}

.role-item:hover {
  border-color: var(--color-primary);
  background-color: rgba(0, 122, 255, 0.05);
}

.role-item--selected {
  border-color: var(--color-primary);
  background-color: rgba(0, 122, 255, 0.1);
}

.role-info {
  flex: 1;
  min-width: 0;
}

.role-name {
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: var(--spacing-xs);
}

.role-description {
  font-size: 12px;
  color: var(--text-secondary);
  line-height: 1.4;
}

.role-checkbox {
  margin-left: var(--spacing-md);
}

.apple-switch--small {
  width: 32px;
  height: 18px;
  border-radius: 9px;
}

.apple-switch--small::before {
  width: 14px;
  height: 14px;
  top: 2px;
  left: 2px;
}

.apple-switch--small.apple-switch--active::before {
  transform: translateX(14px);
}

.apple-card__footer {
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .modal-overlay {
    padding: var(--spacing-md);
  }
  
  .large-dialog {
    max-height: 95vh;
  }
  
  .form-row {
    grid-template-columns: 1fr;
  }
  
  .roles-selection {
    grid-template-columns: 1fr;
  }
  
  .apple-card__footer {
    flex-direction: column-reverse;
    gap: var(--spacing-sm);
  }
  
  .apple-card__footer .apple-button {
    width: 100%;
  }
}
</style>